package com.sea.physical.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.physical.entity.CreateDistributePlan;
import com.sea.physical.entity.CreateDistributeSku;
import com.sea.physical.entity.CreatePlanSupplierFile;
import com.sea.physical.service.*;
import com.sea.supply.entity.ProduceDetail;
import com.sea.supply.entity.WareDistribute;
import com.sea.supply.service.ProduceDetailService;
import com.sea.supply.service.SupplierService;
import com.sea.supply.service.WareDistributeService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 分配创建发运计划
 * @author 陈鸿飞
 */
@Controller
@RequestMapping(value = "/sea/physical/distribute/auto")
public class CreateDistributeAutoController {
    @Autowired
    private CreateDistributePlanService createDistributePlanService;
    @Autowired
    private WareDistributeService wareDistributeService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private CreateDistributeSkuService createDistributeSkuService;

    @Autowired
    private CreatePlanSupplierFileService createPlanSupplierFileService;

    @Autowired
    private OAuth2ClientService oAuth2ClientService;


    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        return "/sea/physical/createDistribute/autoMain";
    }


    /**
     * 自动分配计划
     * @param createId
     * @return
     */
    @RequestMapping("/AutoDistribute")
    @ResponseBody
    public AjaxReturn autoDistribute(@RequestParam("createId")Integer createId){
        AjaxReturn result = Ajax.fail().setMsg("取消失败！");
        try {
            createDistributeSkuService.autoDistribute(createId);
            result.setOk(true).setMsg("自动分配成功！"+createId);
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @RequestMapping("/cancelAutoDistribute")
    @ResponseBody
    public AjaxReturn cancelAutoDistribute(@RequestParam("createId")Integer createId){
        AjaxReturn result = Ajax.fail().setMsg("取消失败！");
        try {
            createDistributePlanService.cancelAutoDistribute(createId);
            result.setOk(true).setMsg("取消成功！");
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @RequestMapping("/sureAutoDistribute")
    @ResponseBody
    public AjaxReturn sureAutoDistribute(@RequestParam("createId")Integer createId){
        AjaxReturn result = Ajax.fail().setMsg("取消失败！");
        try {
            createDistributePlanService.sureAutoDistribute(createId);
            result.setOk(true).setMsg("确认分配成功！");
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }
    @RequestMapping("/importAutoDistribute")
    @ResponseBody
    public AjaxReturn importAutoDistribute(Model model,
                                           MultipartFile importSession,
                                           @RequestParam("createId")Integer createId){
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == importSession || importSession.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = importSession.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                InputStream is = importSession.getInputStream();

                createDistributeSkuService.importAutoSku(is,fileName,createId);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        } catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }
    /**
     * 导出excel
     * @param response
     * @param ids
     */
    @ResponseBody
    @RequestMapping(value = "/export")
    public void export(HttpServletResponse response, @RequestParam("ids") Integer ids[])
    {
        List<CreateDistributeSku> skuList=new ArrayList<>();
        skuList = createDistributeSkuService.getRows(ids);
        String[] title = {"PO号","供应商","渠道","SKU","分配数量","预计交期"};
        String fileName = "分配表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "分配表";
        String[][] content = new String[skuList.size()][6];
        for (int i = 0; i < skuList.size(); i++) {
            content[i] = new String[title.length];
            CreateDistributeSku obj = skuList.get(i);
            content[i][0] = obj.getErpProducePo();
            content[i][1] = obj.getCreateSupplierName();
            content[i][2] = obj.getCreateChannelName();
            content[i][3] = obj.getCreateSku();
            content[i][4] = obj.getCreateNumber() + "";
            content[i][5] = obj.getOrderDate();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }





    /**
     * 导出excel
     * @param response
     * @param id
     */
    @ResponseBody
    @RequestMapping(value = "/exportAuto")
    public void exportAuto(HttpServletResponse response, @RequestParam("id") Integer id)
    {
        List<CreateDistributeSku> exportList=new ArrayList<>();

        List<CreateDistributeSku> skuList=createDistributeSkuService.findByCreateId(id);
        for(CreateDistributeSku createDistributeSku:skuList){
            CreateDistributeSku exportDistributeSku=new CreateDistributeSku();
            String createSupplierName = createDistributeSku.getCreateSupplierName();
            String supplierWare = supplierService.findBySupplierName(createSupplierName).getSupplierWare();
            if(supplierWare.equals("是")){
                WareDistribute wareDistribute = wareDistributeService.findById(createDistributeSku.getCreateProduceId());
                exportDistributeSku.setErpProducePo(wareDistribute.getProduceNo());
                exportDistributeSku.setCreateSupplierName(createDistributeSku.getCreateSupplierName());
                exportDistributeSku.setCreateChannelName(wareDistribute.getReceiveChannelName());
                exportDistributeSku.setCreateSku(wareDistribute.getReceiveSku());
                exportDistributeSku.setCreateNumber(createDistributeSku.getCreateNumber());
            }else{
                CreateDistributeSku dSku = createDistributeSkuService.findDetailById(createDistributeSku.getId());
                exportDistributeSku.setErpProducePo(dSku.getErpProducePo());
                exportDistributeSku.setCreateSupplierName(createDistributeSku.getCreateSupplierName());
                exportDistributeSku.setCreateChannelName(dSku.getCreateChannelName());
                exportDistributeSku.setCreateSku(dSku.getCreateSku());
                exportDistributeSku.setCreateNumber(createDistributeSku.getCreateNumber());
                exportDistributeSku.setOrderDate(dSku.getOrderDate());
            }
            exportList.add(exportDistributeSku);
        }
        String[] title = {"PO号","供应商","渠道","SKU","分配数量","预计交期"};
        String fileName = "分配表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "分配表";
        String[][] content = new String[exportList.size()][6];
        for (int i = 0; i < exportList.size(); i++) {
            content[i] = new String[title.length];
            CreateDistributeSku obj = exportList.get(i);
            content[i][0] = obj.getErpProducePo();
            content[i][1] = obj.getCreateSupplierName();
            content[i][2] = obj.getCreateChannelName();
            content[i][3] = obj.getCreateSku();
            content[i][4] = obj.getCreateNumber() + "";
            content[i][5] = obj.getOrderDate();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/sendFw")
    @ResponseBody
    public AjaxReturn sendFw(@RequestParam("id") Integer id) throws Exception {
        AjaxReturn result = Ajax.fail().setMsg("推送失败！");
        try {


            String accessToken = oAuth2ClientService.getToken();
            if(StringUtils.isNotBlank(accessToken)){
                createDistributePlanService.uploadFwFile(id,accessToken);
                createDistributePlanService.sendFwPostData(id,accessToken);
                return result.setOk(true).setMsg("推送成功!");
            }else {
                return result;
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
            return result.setMsg("系统异常,请联系管理员");

        }


    }



    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }




}
